
package com.ibm.factories;

import java.util.List;

import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ibm.cps.message.MessageFields;
import com.ibm.datamodel.timeseries.SchemaField;
import com.ibm.datamodel.timeseries.TimeSeriesSchema;
import com.ibm.datamodel.timeseries.SchemaField.FieldType;
import com.ibm.interfaces.ITimeSeriesSchema;
import com.ibm.util.DataTypes;
import com.ibm.util.JSONUtility;
import com.ibm.util.exception.CPSException;

public class TimeSeriesSchemaFactory {
	/**
	 * get schema instance according to metadata 
	 * @param tenantid
	 * @param schemaId
	 * @param metadata
	 * @return
	 * @throws CPSException
	 */
	static public ITimeSeriesSchema createFromOtherMetadata(String tenantid,
			String schemaId, ObjectNode metadata) throws CPSException {
		return new TimeSeriesSchema(tenantid, schemaId, (ArrayNode)metadata.get(MessageFields.SCHEMA), -1L);
	}
	
	public static ITimeSeriesSchema createFromSchemaMetadata(String tenantId, String schemaId, ArrayNode node)
			throws CPSException {
		return new TimeSeriesSchema(tenantId, schemaId, node, -1);
	}
	
	public static ITimeSeriesSchema createFromFieldDefinition(String tenantId, String schemaId, List<SchemaField> fields) throws CPSException{
		ArrayNode nodes = JSONUtility.newArrayNode();
		for (SchemaField field : fields) {
			ObjectNode fieldNode = createFieldNode(field);
			nodes.add(fieldNode);
		}
		return createFromSchemaMetadata(tenantId, schemaId, nodes);
	}
	
	public static ITimeSeriesSchema createFromFieldDefinition(String tenantId, String schemaId, SchemaField... fields) throws CPSException{
		ArrayNode nodes = JSONUtility.newArrayNode();
		for (SchemaField field : fields) {
			ObjectNode fieldNode = createFieldNode(field);
			nodes.add(fieldNode);
		}
		return createFromSchemaMetadata(tenantId, schemaId, nodes);
	}
	
	private static ObjectNode createFieldNode(SchemaField field){
		ObjectNode fieldNode = JSONUtility.newObjectNode();
		fieldNode.put(MessageFields.NAME, field.getName());
		fieldNode.put(MessageFields.DATATYPE, DataTypes.getDataType(field.getDataType()));
		SchemaField.FieldType type = field.getFieldType();
		if(type == FieldType.TIMESTAMP){
			fieldNode.put(MessageFields.ISTIME, true);
		} else if(type == FieldType.TS_KEY){
			fieldNode.put(MessageFields.ISKEY, true);
		}
		return fieldNode;
	}

}
